package com.wsx.ones.monitor.core.serialize.hession;

import com.wsx.ones.monitor.core.codec.MessageCodec;
import io.netty.buffer.ByteBuf;

import java.io.IOException;

/**
 * hesiion的编码，解码核心实现
 *
 * Created by wangshuaixin on 17/2/6.
 */
public class HessionMessageCodec implements MessageCodec {

    /**
     * 编码，后期可以扩展自定义的协议
     * @param byteBuf
     * @param message
     * @throws IOException
     */
    @Override
    public void encode(final ByteBuf byteBuf, final Object message) throws IOException {
        Hession2Serialization serialization = new Hession2Serialization();
        byte[] bytes = serialization.serializ(message);
        int bodyLength = bytes.length;
        //消息体的长度
        byteBuf.writeInt(bodyLength);
        //消息体的内容
        byteBuf.writeBytes(bytes);
    }

    /**
     * 解码
     * @param bytes
     * @return
     * @throws IOException
     */
    @Override
    public Object decode(byte[] bytes) throws IOException {
        Hession2Serialization serialization = new Hession2Serialization();
        return serialization.deserializ(bytes);
    }
}
